package com.runrun.com.runrun.sqlsession;

import com.runrun.config.BoundSql;
import com.runrun.pojo.Configuration;
import com.runrun.pojo.MappedStatement;
import com.runrun.utils.GenericTokenParser;
import com.runrun.utils.ParameterMapping;
import com.runrun.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimplleExecutor implements Executor {
    public <E> List<E> Query(Configuration configuration, MappedStatement mappedStatement, Object...parms) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        //获取jdbc连接
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql语句
        String sql = mappedStatement.getSql();
        //将sql语句进行占位符处理
        BoundSql boundSql = getBondSql(sql);
        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        //设置参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> queryClass = getClassType(paramterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = queryClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(parms[0]);
            preparedStatement.setObject(i + 1, o);
        }
        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<Object>();
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method method = propertyDescriptor.getWriteMethod();
                method.invoke(o, value);
            }
            objects.add(o);
        }
        return (List<E>) objects;
    }


    public Integer insert(Configuration configuration, MappedStatement mappedStatement, Object... parms) throws Exception {
        //获取jdbc连接
        Connection connection = configuration.getDataSource().getConnection();
        //处理sql
        String insertSql = mappedStatement.getSql();
        BoundSql boundSql = getBondSql(insertSql);
        //预处理
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        //设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        String paramterType = mappedStatement.getParamterType();
        Class<?> parametrTypeClass = getClassType(paramterType);
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parametrTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(parms[0]);
            preparedStatement.setObject(i + 1, o);

        }
        //执行sql
        boolean execute = preparedStatement.execute();
        if (execute) {
            return 1;
        }
        return 0;
    }

    public Integer update(Configuration configuration, MappedStatement mappedStatement, Object... parms) throws Exception {
        //获取jdbc连接
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql
        String updateSql = mappedStatement.getSql();
        //对sql进行占位符处理，就是将#{}替换成？
        BoundSql boundSql = getBondSql(updateSql);
        //预处理
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        //设置参数,获取参数类型
        String parmterType = mappedStatement.getParamterType();
        //获取sql语句中的#{}里面的内容
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        //使用反射，
        Class<?> classType = getClassType(parmterType);
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = classType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(parms[0]);
            preparedStatement.setObject(i+1,o);
        }
        int updateNum = preparedStatement.executeUpdate();
        return updateNum;
    }

    public Integer delete(Configuration configuration, MappedStatement mappedStatement, Object... parms) throws Exception {
        //获取jdbc连接
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql
        String deleteSql = mappedStatement.getSql();
        //对sql 进行占位符处理
        BoundSql boundSql = getBondSql(deleteSql);
        //预处理
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        //设置参数，获取参数类型
        String paramterType = mappedStatement.getParamterType();
        //获取#{}里的内容
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        //使用反射
        Class<?> classType = getClassType(paramterType);
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = classType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(parms[0]);
            preparedStatement.setObject(i+1,o);
        }
        boolean execute = preparedStatement.execute();
        if(execute){
            return 1;
        }
        return 0;
    }

    private BoundSql getBondSql(String sql) {
        //标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappingList = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappingList);
        return boundSql;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            Class<?> classType = Class.forName(paramterType);
            return classType;
        }
        return null;
    }

}
